package com.example.fill.Test240126;

import java.util.*;
import java.util.concurrent.*;
import java.util.function.Consumer;
import java.util.function.Supplier;

public class IOManager {
    private final List<Commend> allCommends = new ArrayList<>();
    private final ConcurrentHashMap<Commend,ScheduledFuture> waitingCommend = new ConcurrentHashMap<>();

    //private final ExecutorService poll = new ThreadPoolExecutor(10,3,4,TimeUnit.SECONDS,new LinkedBlockingQueue<>());
    private final ScheduledExecutorService timer = Executors.newSingleThreadScheduledExecutor();
    Listener listener;

    public IOManager(Listener listener) {
        this.listener = listener;
    }

    public void putCommend(Commend commend){
        allCommends.add(commend);
        listener.onSend(commend);
        ScheduledFuture<?> scheduledFuture = timer.schedule(new CuntDownTimerTask(commend),  5, TimeUnit.SECONDS);
        waitingCommend.put(commend,scheduledFuture);
        System.out.println(commend.getToken().toString() + "已加入等待任务列表");
    }

    public void receiveCommend(byte[] b, UUID uuid){
        Commend commendR = waitingCommend.keySet().stream()
                .filter(commend -> commend.getToken() == uuid)
                .findFirst()
                .orElseGet(new Supplier<Commend>() {
                    @Override
                    public Commend get() {
                        return new Commend()
                                .setToken(UUID.randomUUID());
                    }
                });
            ScheduledFuture<?> scheduledFuture = waitingCommend.get(commendR);
            if (scheduledFuture == null){
                listener.onUnknown(commendR);
                System.out.println("----------------------未在等待列表当中找到此命令:"+uuid);
                return;
            }
            scheduledFuture.cancel(true);
            commendR.setNoBack(false);
            commendR.setBackTime(System.currentTimeMillis());
            commendR.setBackData(b);
            listener.onReceive(commendR);
            waitingCommend.remove(commendR);
            System.out.println("命令同步成功，等待列表已移除");
    }

    private class CuntDownTimerTask implements Runnable {
        Commend commend;

        public CuntDownTimerTask(Commend commend) {
            this.commend = commend;
        }

        @Override
        public void run() {
            commend.setNoBack(true);
            commend.setBackTime(System.currentTimeMillis());
            listener.onTimeOut(commend);
            waitingCommend.remove(commend);
            System.out.println("-------------------等待超时，移除等待，取消任务:"+commend.getToken());
        }
    }


}
